"""
搜索url：https://complexsearch.kugou.com/v2/search/song
歌曲信息页：https://wwwapi.kugou.com/yy/index.php
https://webfs.yun.kugou.com/202011291548/00665bd6a87f99ae4058f935c63d1941/part/0/964146/G199/M05/1F/14/p5QEAF5xsMSAFYayAD5UFkMtfIc273.mp3
当前时间/
"""
import re
import os
import json
import time
import hashlib
import requests


def signature():
    o = [
        "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt",
        "bitrate=0", "callback=callback123",
        "clienttime={}".format(time_now),
        "clientver=2000",
        "dfid=-",
        "inputtype=0",
        "iscorrection=1",
        "isfuzzy=0",
        "keyword={}".format(keyword),
        "mid={}".format(time_now),
        "page=1",
        "pagesize=30",
        "platform=WebFilter",
        "privilege_filter=0",
        "srcappid=2919",
        "tag=em",
        "userid=-1",
        "uuid={}".format(time_now),
        "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt"
    ]
    sig = ''.join(o)
    # 1. 初始化md5
    md5 = hashlib.md5()
    # 2. 加密
    md5.update(sig.encode('utf-8'))
    # 3. 返回加密数据
    return md5.hexdigest()


def search():
    params = {
        'callback': 'callback123',
        'keyword': keyword,
        'page': '1',
        'pagesize': '30',
        'bitrate': '0',
        'isfuzzy': '0',
        'tag': 'em',
        'inputtype': '0',
        'platform': 'WebFilter',
        'userid': '-1',
        'clientver': '2000',
        'iscorrection': '1',
        'privilege_filter': '0',
        'srcappid': '2919',
        'clienttime': time_now,
        'mid': time_now,
        'uuid': time_now,
        'dfid': '-',
        'signature': signature(),
    }
    sear = requests.get(url=search_url, params=params, headers=headers).text
    sear2 = re.compile(r'\((.*)\)').findall(sear)[0]
    res = json.loads(sear2)
    songs_list = res['data']['lists']
    # print(songs_list)
    # 循环查询的列表
    for song in songs_list:
        AlbumID = song['AlbumID']
        if song['HQFileHash']:
            FileHash = song['HQFileHash']
        else:
            FileHash = song['FileHash']
        song_detail(FileHash, AlbumID)


def song_get(url, song_name):
    song = requests.get(url=url, headers=headers)
    with open(song_name+'.mp3', 'wb')as s:
        s.write(song.content)
    print(song_name, '保存成功')


def song_detail(hash, AlbumID):
    callback = 'jQuery19101927348916106959_' + str(time_now)
    params = {
        'r': 'play/getdata',
        'callback': callback,
        'hash': hash,
        'dfid': '3dPQ7x2bWFuR13sQtR17p4mU',  # 固定
        'mid': 'b0e5cd12eecef8bd34a0b531d2638467',  # 固定
        'platid': '4',  # 固定
        'album_id': AlbumID,
        '_': time_now + 1
    }
    res = requests.get(song_url, params=params, headers=headers)
    res2 = re.compile(r'\((.*)\)').findall(res.text)
    if res2:
        res3 = json.loads(res2[0])
        song_href = res3['data']['play_url']
        if song_href:
            song_name = res3['data']['song_name']
            song_get(song_href, song_name)
        else:
            print('此歌曲无法下载')


if __name__ == '__main__':
    keyword = input('输入查询的歌曲信息：')
    time_now = round(time.time()*1000)
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
        'cookie': 'kg_mid=b0e5cd12eecef8bd34a0b531d2638467; kg_dfid=3dPQ7x2bWFuR13sQtR17p4mU; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1606624441; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1606631835'
    }
    if not os.path.exists('音乐'):
        os.mkdir('音乐')
    os.chdir('音乐')
    if not os.path.exists(keyword):
        os.mkdir(keyword)
    os.chdir(keyword)
    search_url = 'https://complexsearch.kugou.com/v2/search/song'
    song_url = 'https://wwwapi.kugou.com/yy/index.php'
    search()











